has_pic = false
has_command = false
bot_status = "stop"
GENERATION_SUCCESS = 0
GENERATION_ERROR = 0

function random_user() {
    user = document.cookie
    if (user != '') {
        return user;
    }
    else{
        var randomString = '';
        for (var i = 0; i < 10; i++) {
            var randomInt = Math.floor(Math.random() * 26);
            var randomChar = String.fromCharCode(randomInt + 65);
            randomString += randomChar;
        }
        document.cookie=randomString;
        return randomString;
    }
}

user_id = random_user()
control_available = false

function alert(msg) {
    Toast(msg, 3000);
}

function e_log(e, msg) {
    console.log(e);
    alert(msg);
}

function prompt_gen() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (bot_status != 'stop') {
        alert("机械臂未处于空闲状态");
        return;
    }

    var prompt = document.getElementById('prompt_input').value;
    generating();
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "prompt", "prompt": prompt }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            has_pic = true;
            GENERATION_SUCCESS = 1;
            var bg_style = "url('" + res['pic_url'] + "')";
            document.getElementById('color_pic').style.backgroundImage = bg_style;
        },
        error: function (err) {
            e_log(err, '连接到后端失败');
            GENERATION_ERROR = 1;
        }
    });
}

function file_change(f) {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (bot_status != 'stop') {
        alert("机械臂未处于空闲状态");
        return;
    }

    let file = f.target.files[0]
    if (file) {
        const fileSize = file.size
        const isLt5M = fileSize / 1024 / 1024 < 5
        if (!isLt5M) {
            e_log('Gt5M', '上传文件大小不超过5MB');
            f.target.value = '';
            return;
        }
        const name = file.name
        const fileName = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
        if (
            fileName !== 'jpeg' &&
            fileName !== 'jpg' &&
            fileName !== 'png' &&
            fileName !== 'bmp'
        ) {
            e_log('not pic', '请选择格式文件(jpg jpeg png bmp)上传！');
            f.target.value = '';
            return;
        }
        document.getElementById('file_path').innerHTML = name;
    }
}

function file_upload() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (bot_status != 'stop') {
        alert("机械臂未处于空闲状态");
        return;
    }
    if (document.getElementById('file_input').value == '') {
        alert("请选择要上传的图片！");
        return false;
    }

    var formData = new FormData();
    formData.append(
        'file',
        document.getElementById('file_input').files[0]
    );
    $.ajax({
        url: "./file_upload",
        type: "post",
        data: formData,
        processData: false,
        contentType: false,
        success: function (res) {
            console.log(res);
            document.getElementById('file_input').value = '';
            document.getElementById('file_path').innerHTML = name;
            has_pic = true;
            var bg_style = "url('" + res['pic_url'] + "')";
            document.getElementById('color_pic').style.backgroundImage = bg_style;
        },
        error: function (err) {
            e_log(err, "图片上传失败");
        }

    })

}

function pic_trans() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (!has_pic) {
        alert("您还没有上传/生成图片");
        return;
    }
    var prompt = document.getElementById('prompt_input').value;
    generating();
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "pic_trans", "prompt": prompt }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            GENERATION_SUCCESS = 1;
            var bg_style = "url('" + res['pic_url'] + "')";
            document.getElementById('color_pic').style.backgroundImage = bg_style;
        },
        error: function (err) {
            e_log(err, '风格迁移失败');
            GENERATION_ERROR = 1;
        }
    });
}

function command_gen() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (bot_status != 'stop') {
        alert("机械臂未处于空闲状态");
        return;
    }
    if (!has_pic) {
        alert("您还没有上传/生成图片");
        return;
    }
    var blur = document.getElementById('blur').value
    var gate = document.getElementById('gate').value
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            "command": "code_generate",
            "blur": blur,
            "gate": gate
        }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            has_command = true;
            var bg_style = "url('" + res['pic_url'] + "')";
            document.getElementById('line_pic').style.backgroundImage = bg_style;
        },
        error: function (err) {
            e_log(err, '绘画指令生成失败');
        }
    });
}

function run_pause() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (!has_command) {
        alert("您还没有生成指令");
        return;
    }
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "run_pause" }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            btn_text = document.getElementById('run_pause_btn').innerText
            if (bot_status == "pause" || bot_status == "stop") {
                bot_status = "running";
                document.getElementById('run_pause_btn').innerText = "暂停";
                document.getElementById('run_pause_btn_b').innerText = "暂停";
            }
            else {
                if (bot_status == "running") {
                    bot_status = "pause";
                    document.getElementById('run_pause_btn').innerText = "继续";
                    document.getElementById('run_pause_btn_b').innerText = "继续";
                }
            }
            status_check();
        },
        error: function (err) {
            e_log(err, '启停指令下发失败');
        }
    });
}

function stop() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (bot_status == "stop") {
        alert("机械臂未处于运行状态");
        return;
    }
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "stop" }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            bot_status = "stop";
            document.getElementById('run_pause_btn').innerText = "启动";
            document.getElementById('run_pause_btn_b').innerText = "启动";
            status_check();

        },
        error: function (err) {
            e_log(err, '终止指令下发失败');
        }
    });
}

function height_tune(direction) {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    if (bot_status != "stop") {
        alert("机械臂正在工作，无法调整");
        return;
    }
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "tune", "direction": direction }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            status_check();
        },
        error: function (err) {
            e_log(err, '微调指令下发失败');
        }
    });
}

function slider_sync(i) {
    var id = i.target.id;
    var val = i.target.value;
    var id_change = '';
    if (id[4] == '_') {
        id_change = id.substr(0, 4);
    }
    else {
        id_change = id + '_b';
    }
    document.getElementById(id_change).value = val;
    document.getElementById(id + '_value').innerHTML = val;
    document.getElementById(id_change + '_value').innerHTML = val;
}

function status_check() {
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "status_check" }),
        dataType: "json",
        success: function (res) {
            console.log(res);
            if (res['code'] == 0) {
                bot_status = "stop";
                document.getElementById('status').innerHTML = '机械臂状态：<span style="color:green;">空闲</span>';
            }
            if (res['code'] == 1) {
                bot_status = "running";
                document.getElementById('status').innerHTML = '机械臂状态：<span style="color:blue;">运行中</span>';
                document.getElementById('run_pause_btn').innerText = "暂停";
                document.getElementById('run_pause_btn_b').innerText = "暂停";
            }
            if (res['code'] == 2) {
                bot_status = "pause";
                document.getElementById('status').innerHTML = '机械臂状态：<span style="color:orange;">暂停中</span>';
                document.getElementById('run_pause_btn').innerText = "继续";
                document.getElementById('run_pause_btn_b').innerText = "继续";
            }
        },
        error: function (err) {
            e_log(err, '连接到后端失败');
        }
    });
}

function Toast(msg, duration) {
    duration = isNaN(duration) ? 3000 : duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.className = "toast";
    m.style.animationDuration = '' + duration / 1000 + 's';
    document.body.appendChild(m);
    setTimeout(function () { document.body.removeChild(m) }, 0.9 * duration);
}

function pic_clean() {
    if (!control_available) { alert('当前机械臂已有其他设备进行控制'); return; }
    $.ajax({
        url: "./post",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "command": "pic_clean" }),
        dataType: "json",
        success: function (res) {
            console.log(res);
        },
        error: function (err) {
            console.log('清理失败', err);
        }
    });
}

function heart_beat() {
    $.ajax({
        url: "./heartbeat",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ "user_id": user_id }),
        dataType: "json",
        success: function (res) {
            if (res['status'] == 'OK') {
                control_available = true;
                status_check();
                setTimeout(heart_beat, 3000);
            } else {
                control_available = false;
                console.log(res);
                alert('当前机械臂已有其他设备进行控制');
            }
        },
        error: function (err) {
            console.log('心跳服务连接失败', err);
        }
    });
}

function set_percent(per) {
    $(function () {
        var percent = per;
        var baseColor = $('.circle-bar').css('background-color');
        document.getElementById("percent_num").innerHTML = per + '%';
        if (percent <= 50) {
            $('.circle-bar-right').css('transform', 'translate(-50%, -50%) rotate(' + (percent * 3.6) + 'deg)');
        } else {
            $('.circle-bar-right').css({
                'transform': 'translate(-50%, -50%) rotate(0deg)',
                'background-color': baseColor
            });
            $('.circle-bar-left').css('transform', 'translate(-50%, -50%) rotate(' + ((percent - 50) * 3.6) + 'deg)');
        }
    })
}

function generating(per = 0) {
    var dt = 25 / 100.0;
    document.getElementsByClassName('circle-bar-left')[0].style = '';
    document.getElementsByClassName('circle-bar-right')[0].style = '';
    document.getElementById('per').style.display = 'block'
    set_percent(per);
    if (GENERATION_ERROR){
        document.getElementById('per').style.display = 'none';
        return;
    }
    if (per < 95) {
        setTimeout(generating, dt * 1000, per = per + 1);
        return;
    }
    if (per >= 95 & per < 100) {
        setTimeout(generating, dt * 1000, per = per + GENERATION_SUCCESS);
        return;
    }
    if (per == 100) {
        document.getElementById('per').style.display = 'none';
        GENERATION_SUCCESS = 0;
        return;
    }

}

document.getElementById('prompt_btn').addEventListener('click', function () { prompt_gen() });
document.getElementById('file_input').addEventListener('change', function (f) { file_change(f) });
document.getElementById('upload_btn').addEventListener('click', function () { file_upload() });
document.getElementById('trans_btn').addEventListener('click', function () { pic_trans() });
document.getElementById('vect_btn').addEventListener('click', function () { command_gen() });
document.getElementById('vect_btn_b').addEventListener('click', function () { command_gen() });
document.getElementById('run_pause_btn').addEventListener('click', function () { run_pause() });
document.getElementById('run_pause_btn_b').addEventListener('click', function () { run_pause() });
document.getElementById('stop_btn').addEventListener('click', function () { stop() });
document.getElementById('stop_btn_b').addEventListener('click', function () { stop() });
document.getElementById('blur').addEventListener('change', function (i) { slider_sync(i) });
document.getElementById('blur_b').addEventListener('change', function (i) { slider_sync(i) });
document.getElementById('gate').addEventListener('change', function (i) { slider_sync(i) });
document.getElementById('gate_b').addEventListener('change', function (i) { slider_sync(i) });
document.getElementById('up_btn').addEventListener('click', function () { height_tune("up") });
document.getElementById('up_btn_b').addEventListener('click', function () { height_tune("up") });
document.getElementById('down_btn').addEventListener('click', function () { height_tune("down") });
document.getElementById('down_btn_b').addEventListener('click', function () { height_tune("down") });

status_check();
heart_beat();